<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问题类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择问题类型" clearable>
          <el-option
              v-for="dict in medical_problem_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="问题类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择问题类别" clearable>
          <el-option
              v-for="dict in medical_problem_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否起始问题" prop="start">
        <el-select v-model="queryParams.start" placeholder="请选择是否起始问题" clearable>
          <el-option
              v-for="dict in medical_problem_start"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="问题名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入问题名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问题描述" prop="description">
        <el-input
            v-model="queryParams.description"
            placeholder="请输入问题描述"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="memo">
        <el-input
            v-model="queryParams.memo"
            placeholder="请输入备注"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['medical:problem:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['medical:problem:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['medical:problem:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="doReleation"
        >知识图谱
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="problemList" @selection-change="handleSelectionChange"
              :row-class-name="rowIndex">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="index" width="50"/>
      <el-table-column v-if="false" label="问题id" align="center" prop="id"/>
      <el-table-column label="问题类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="medical_problem_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="问题类别" align="center" prop="category">
        <template #default="scope">
          <dict-tag :options="medical_problem_category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="是否起始问题" align="center" prop="start">
        <template #default="scope">
          <dict-tag :options="medical_problem_start" :value="scope.row.start"/>
        </template>
      </el-table-column>
      <el-table-column label="问题名称" align="center" prop="name"/>
      <el-table-column label="问题描述" align="center" prop="description"/>
      <el-table-column label="备注" align="center" prop="memo"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['medical:problem:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['medical:problem:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Search" @click="viewReleation(scope.row)">查看图谱</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改中医问题对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="problemRef" :model="form" :inline="true" :rules="rules" label-width="90px">
        <el-form-item v-if="false" label="目标点" prop="target">
          <el-select v-model="form.target" placeholder="目标点" filterable clearable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择问题类型">
            <el-option
                v-for="dict in medical_problem_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择问题类别">
            <el-option
                v-for="dict in medical_problem_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题名称" prop="name">
          <el-input v-model="form.name" style="width: 1000px" placeholder="请输入问题名称"/>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input type="textarea" :rows="3" style="width: 1000px" v-model="form.description"
                    placeholder="请输入问题描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input type="textarea" :rows="3" style="width: 1000px" v-model="form.memo" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">中医问题答案信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMedicalProblemAnswer">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteMedicalProblemAnswer">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="medicalProblemAnswerList" :row-class-name="rowMedicalProblemAnswerIndex"
                  @selection-change="handleMedicalProblemAnswerSelectionChange" ref="medicalProblemAnswer">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="答案" prop="answer" width="500">
            <template #default="scope">
              <el-input v-model="scope.row.answer" placeholder="请输入答案"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="memo" width="500">
            <template #default="scope">
              <el-input v-model="scope.row.memo" placeholder="请输入备注"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="releationTitle" v-model="releationOpen" width="600px" append-to-body>
      <el-form ref="problemRleationRef" :model="releationForm" :inline="true" :rules="rules" label-width="90px">

        <el-form-item v-if="false" label="答案" prop="source">
          <el-select v-model="releationForm.target" placeholder="请选择答案" filterable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="问题" prop="target">
          <el-select v-model="releationForm.source" placeholder="请选择问题" filterable>
            <el-option
                v-for="problem in problemData"
                :key="problem.value"
                :label="problem.label"
                :value="problem.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReleationForm">确 定</el-button>
          <el-button @click="cancelReleation">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="releationViewTitle" @open="openReleactionView" v-model="releationViewOpen" width="1200px"
               append-to-body>
      <el-form ref="searchRleationRef" :model="searchForm" :inline="true" :rules="rules"
               label-width="90px">

        <el-form-item label="问题" prop="problemId">
          <el-select v-model="searchForm.problemId" placeholder="请选择问题" filterable clearable
                     @change="handleProblemChange">
            <el-option
                v-for="problem in problemData"
                :key="problem.value"
                :label="problem.label"
                :value="problem.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="答案" prop="answerId">
          <el-select v-model="searchForm.answerId" placeholder="请选择答案" filterable clearable>
            <el-option
                v-for="answer in answerData"
                :key="answer.value"
                :label="answer.label"
                :value="answer.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <div ref="chartContainer" style="width: 1200px; height: 700px;"></div>
      <!-- 自定义的上下文菜单，初始时不显示 -->
      <div ref="contextMenu" class="context-menu" style="display: none;">
        <el-button @click="releationDelete" type="danger" plain icon="Delete">删除关系</el-button>
      </div>

      <div ref="contextNodeMenu" style="display: none;" class="containerMenu">
        <div class="sectionMenu">
          <el-button @click="addReleation" style="margin-left: 13px;" type="primary" plain icon="Plus">创建关系</el-button>
        </div>
        <div class="sectionMenu">
          <el-button @click="deleteProblemAnswerNode" style="margin-left: 13px;" type="primary" plain icon="Delete">删除答案</el-button>
        </div>
        <div class="sectionMenu">
          <el-button @click="addReleationNode" style="margin-left: 13px;" type="primary" plain icon="Edit">添加问题</el-button>
        </div>
      </div>
      <div ref="contextDeleteNodeMenu" style="display: none;">
        <el-button @click="deleteNode" type="primary" plain icon="Delete">删除问题</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="Problem">
import {
  problemAndAnswerList,
  listProblem,
  getProblem,
  delProblem,
  addProblem,
  updateProblem,
  delProblemAnswer
} from "@/api/medical/problem/problem.js";
import {
  delReleation,
  listNodeAndEdge,
  makeReleation,
  queryNodeAndReleation
} from "@/api/medical/releation/releation.js";
import * as echarts from 'echarts';
import {ref} from "vue";

const {proxy} = getCurrentInstance();
const {
  medical_problem_type,
  medical_problem_start,
  medical_problem_category
} = proxy.useDict('medical_problem_type', 'medical_problem_start', 'medical_problem_category');

const problemList = ref([]);
const medicalProblemAnswerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMedicalProblemAnswer = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const releationTitle = ref("");
const releationOpen = ref(false);
const releationViewTitle = ref("");
const releationViewOpen = ref(false);
const problemData = ref([]);
const answerData = ref([]);
let myChart = ref({});
let timmer = ref(null);
let contextMenu = ref(null); // 用于存储自定义的右键菜单
let contextNodeMenu = ref(null);
let contextDeleteNodeMenu = ref(null);

const chartContainer = ref(null);
//节点
const nodes = ref([]);
//关系
const links = ref([]);

const currentNode = ref(null);
const currentSource = ref(null);
const currentTarget = ref(null);

const data = reactive({
  form: {},
  releationForm: {},
  searchForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    category: null,
    start: null,
    name: null,
    description: null,
    memo: null,
  },
  rules: {
    type: [
      {required: true, message: "问题类型不能为空", trigger: "change"}
    ],
    category: [
      {required: true, message: "问题类别不能为空", trigger: "change"}
    ],
    start: [
      {required: true, message: "是否起始问题不能为空", trigger: "change"}
    ],
    name: [
      {required: true, message: "问题名称不能为空", trigger: "blur"}
    ],
    description: [
      {required: true, message: "问题描述不能为空", trigger: "blur"}
    ],
    source: [
      {required: true, message: "起始节点问题答案不能为空", trigger: "change"}
    ],
    target: [
      {required: true, message: "结束节点问题不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, releationForm, searchForm, rules} = toRefs(data);


/** 查询中医问题列表 */
function getList() {
  loading.value = true;
  listProblem(queryParams.value).then(response => {
    problemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    category: null,
    start: null,
    name: null,
    target: null,
    description: null,
    memo: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  medicalProblemAnswerList.value = [];
  proxy.resetForm("problemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function resetSearch() {
  proxy.resetForm("searchRleationRef");
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加中医问题";
}

/**
 * 弹窗选择答案和问题，创建关系
 */
function doReleation() {

  // releationViewOpen.value = true;
  // releationViewTitle.value = "关系维护";
  // queryParams.value.problemIds = [];

  window.open('releation?type=' + 1, "_blank");
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProblem(_id).then(response => {
    form.value = response.data;
    medicalProblemAnswerList.value = response.data.medicalProblemAnswerList;
    open.value = true;
    title.value = "修改中医问题";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["problemRef"].validate(valid => {
    if (valid) {
      form.value.medicalProblemAnswerList = medicalProblemAnswerList.value;
      if (form.value.id != null) {
        updateProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          if (releationViewOpen.value) {
            //刷新一下关系页面
            NodeAndReleation();
          }
          getList();
        });
      } else {
        addProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          if (releationViewOpen.value) {
            //刷新一下关系页面
            NodeAndReleation();
          }
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除中医问题编号为"' + _ids + '"的数据项？').then(function () {
    return delProblem(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 中医问题答案序号 */
function rowMedicalProblemAnswerIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 中医问题答案添加按钮操作 */
function handleAddMedicalProblemAnswer() {
  let obj = {};
  obj.answer = "";
  obj.memo = "";
  medicalProblemAnswerList.value.push(obj);
}

/** 中医问题答案删除按钮操作 */
function handleDeleteMedicalProblemAnswer() {
  if (checkedMedicalProblemAnswer.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的中医问题答案数据");
  } else {
    const medicalProblemAnswers = medicalProblemAnswerList.value;
    const checkedMedicalProblemAnswers = checkedMedicalProblemAnswer.value;
    medicalProblemAnswerList.value = medicalProblemAnswers.filter(function (item) {
      return checkedMedicalProblemAnswers.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleMedicalProblemAnswerSelectionChange(selection) {
  checkedMedicalProblemAnswer.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('medical/problem/export', {
    ...queryParams.value
  }, `problem_${new Date().getTime()}.xlsx`)
}

function rowIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/**
 * 问题列表
 */
function getProblemList() {
  problemAndAnswerList().then(response => {
    problemData.value = [];
    for (var i = 0; i < response.data.length; i++) {
      let problem = {};
      problem.value = response.data[i].id;
      problem.label = response.data[i].name;
      problemData.value.push(problem);
    }
  });
}

/**
 * 切换问题
 */
function handleProblemChange(problemId) {
  releationForm.value.source = null;
  getProblem(problemId).then(response => {
    answerData.value = [];
    for (var i = 0; i < response.data.medicalProblemAnswerList.length; i++) {
      let answer = {};
      answer.value = response.data.medicalProblemAnswerList[i].id;
      answer.label = response.data.medicalProblemAnswerList[i].answer;
      answerData.value.push(answer);
    }
  });
}

/**
 * 取消创建关系
 */
function cancelReleation() {
  releationOpen.value = false;
  releationForm.value = {
    source: null,
    target: null,
    problemId: null
  };
  proxy.resetForm("problemRleationRef");
}

/**
 * 绑定关系
 */
function submitReleationForm() {

  proxy.$refs["problemRleationRef"].validate(valid => {
    if (valid) {
      releationForm.value.target = releationForm.value.target;
      releationForm.value.source = 'PROBLEM' + releationForm.value.source;
      makeReleation(releationForm.value).then(response => {
        releationOpen.value = false;
        proxy.$modal.msgSuccess("新建关系成功");
        NodeAndReleation();
      });
    }
  });
}


const option = {
  legend: {
    data: ['问题', '答案']
  },
  tooltip: {},
  animationDurationUpdate: 1500,
  animationEasingUpdate: 'quinticInOut',
  series: [
    {
      type: 'graph',
      layout: 'none',
      symbolSize: 40,
      roam: true,
      label: {
        show: true
      },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      edgeLabel: {
        fontSize: 20
      },
      tooltip: {
        trigger: 'item',
        triggerOn: 'contextmenu'
      },
      categories: [
        {
          name: '问题',
          keyword: {},
          base: '问题'
        },
        {
          name: '答案',
          keyword: {},
          base: '答案'
        }
      ],
      data: [],
      links: [],
      itemStyle: function (params) {
        if (params.data.category === 'Type A') {
          return {
            color: 'red' // 示例：为Type A的节点设置红色
          };
        } else if (params.data.category === 'Type B') {
          return {
            color: 'blue' // 示例：为Type B的节点设置蓝色
          };
        }
      },
      // force: {
      //   repulsion: 600,
      //   edgeLength: 100
      // },
      // 监听鼠标移入事件
      emphasis: {
        focus: 'adjacency', // 相邻节点也会被高亮
        triggerOn: 'mouseover', // 触发高亮的事件
      },
      lineStyle: {
        opacity: 0.9,
        width: 2,
        curveness: 0
      }
    }
  ]
};


function initGrap() {
  option.series[0].data = nodes.value;
  option.series[0].links = links.value;
  if (queryParams.value.problemIds) {
    if (myChart && myChart.dispose) {
      myChart.dispose();
    }
  }
  // 初始化新实例
  myChart = echarts.init(chartContainer.value);
  myChart.setOption(option);
  // console.log(chartContainer.value, 'myChart1：',myChart);

  myChart.on('contextmenu', (params) => {
    console.log("dataType:" + params.dataType);
    console.log(params);
    if (params.dataType === 'edge' && params.data.source && params.data.source.indexOf("PROBLEM") > -1) {
      params.event.event.preventDefault();
      // 显示上下文菜单
      showContextMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      //记录当前关系的开始节点和结束节点
      currentSource.value = params.data.source;
      currentTarget.value = params.data.target;

      hideContextNodeMenu();
      hideContextDeleteNodeMenu();
    } else if (params.dataType === 'node' && params.data.category === 0) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContextDeleteNodeMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      hideContextMenu();
      hideContextNodeMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else if (params.dataType === 'node' && params.data.category === 1) {
      params.event.event.preventDefault();
      //显示node的菜单
      showContexNodetMenu(params.event.offsetX + 15, params.event.offsetY + 110);
      hideContextMenu();
      hideContextDeleteNodeMenu();
      //记录当前点击的nodeid
      currentNode.value = params.data.id;
    } else {
      hideContextMenu();
      hideContextNodeMenu();
      hideContextDeleteNodeMenu();
    }
  });

  // //随着屏幕大小调节图表
  // window.addEventListener("resize", () => {
  //   console.log('窗口变化啦');
  //   timmer.value = setTimeout(function () {
  //     myChart.resize();
  //   }, 200)
  // });

}

function openReleactionView() {
  nextTick(() => {
    NodeAndReleation();
  });
}

function NodeAndReleation() {
  loading.value = true;
  nodes.value = [];
  links.value = [];
  queryParams.value.releationType = 1;
  queryNodeAndReleation(queryParams.value).then(response => {
    for (var i = 0; i < response.data.nodes.length; i++) {
      let node = {};
      node.id = response.data.nodes[i].id;
      node.name = response.data.nodes[i].name;
      node.category = response.data.nodes[i].category;
      node.x = response.data.nodes[i].x;
      node.y = response.data.nodes[i].y;
      nodes.value.push(node);
    }
    for (var i = 0; i < response.data.links.length; i++) {
      let link = {};
      link.source = response.data.links[i].source;
      link.target = response.data.links[i].target;
      links.value.push(link);
    }
    loading.value = false;
    initGrap();
  });
}

function showContextDeleteNodeMenu(x, y) {

  // 设置菜单的位置
  contextDeleteNodeMenu.value.style.left = `${x}px`;
  contextDeleteNodeMenu.value.style.top = `${y}px`;
  contextDeleteNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  // 显示菜单
  contextDeleteNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextDeleteNodeMenu);
}

// 显示上下文菜单
function showContextMenu(x, y) {
  // 设置菜单的位置
  contextMenu.value.style.left = `${x}px`;
  contextMenu.value.style.top = `${y}px`;
  contextMenu.value.style.position = 'absolute'; // 确保是absolute或fixed

  // 显示菜单
  contextMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextMenu);
}

// 显示上下文菜单
function showContexNodetMenu(x, y) {
  // 设置菜单的位置
  contextNodeMenu.value.style.left = `${x}px`;
  contextNodeMenu.value.style.top = `${y}px`;
  contextNodeMenu.value.style.position = 'absolute'; // 确保是absolute或fixed
  console.log(contextNodeMenu.value);
  // 显示菜单
  contextNodeMenu.value.style.display = 'block';

  // 添加文档点击事件监听器，用于隐藏菜单
  document.addEventListener('click', hideContextNodeMenu);
}

// 隐藏上下文菜单
function hideContextMenu() {
  if (contextMenu.value) {
    contextMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextMenu);
}

//隐藏菜单
function hideContextNodeMenu() {
  if (contextNodeMenu.value) {
    contextNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextNodeMenu);
}

function hideContextDeleteNodeMenu() {
  if (contextDeleteNodeMenu.value) {
    contextDeleteNodeMenu.value.style.display = 'none';
  }
  document.removeEventListener('click', hideContextDeleteNodeMenu);
}

// 处理删除操作
function releationDelete() {
  // 这里可以编写实际的删除逻辑
  form.value.source = currentSource.value;
  form.value.target = currentTarget.value;
  delReleation(form.value).then(response => {
    proxy.$modal.msgSuccess("删除关系成功");
    //触发视图渲染
    NodeAndReleation();
  });

  // 删除后隐藏菜单
  hideContextMenu();
}

function handleSearch() {

  if (!searchForm.value.problemId && !searchForm.value.answerId) {
    return;
  }
  let nodeId = "";
  if (searchForm.value.answerId) {
    nodeId = 'ANSWER' + searchForm.value.answerId;
  }
  if (!nodeId) {
    nodeId = 'PROBLEM' + searchForm.value.problemId;
  }
  const data = myChart.getOption().series[0].data;
  const nodeIndex = data.findIndex(node => node.id === nodeId);

  if (nodeIndex !== -1) {
    // 定位到节点
    myChart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: nodeIndex
    });

  }
}

function addReleation() {
  releationForm.value.source = null;
  releationOpen.value = true;
  releationTitle.value = "关系创建";
  releationForm.value.target = currentNode.value;

}

function addReleationNode() {
  handleAdd();
  form.value.target = currentNode.value;
}

function viewReleation(row) {
  //查看当前节点的知识图谱信息
  let problemIds = [];
  problemIds.push(row.id);
  queryParams.value.problemIds = problemIds;
  releationViewOpen.value = true;
  releationViewTitle.value = "关系维护";
}

function deleteNode() {
  const _ids = currentNode.value.replace("PROBLEM", "");
  proxy.$modal.confirm('是否确认删除此问题？').then(function () {
    return delProblem(_ids);
  }).then(() => {
    getList();
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/**
 * 删除问题答案
 */
function deleteProblemAnswerNode() {
  const _ids = currentNode.value.replace("ANSWER", "");
  proxy.$modal.confirm('是否确认删除此问题答案？').then(function () {
    return delProblemAnswer(_ids);
  }).then(() => {
    NodeAndReleation();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

getList();
getProblemList();
</script>
<style scoped>
.custom-context-menu {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 5px;
  /* 其他样式 */
}

.containerMenu {
  width: 140px; /* 宽度 */
  height: 180px; /* 高度 */
  position: relative; /* 设置为相对定位，以便内部元素可以相对于它定位（虽然在这个例子中不是必需的） */
  border: 1px solid #ccc; /* 可选：给容器添加边框以便更清楚地看到它 */
  background-color: #fff; /* 背景色，可能需要与边框色对比 */
  border-radius: 8px;
}

.sectionMenu {
  margin-top: 12px;
  width: 100%; /* 宽度占满父容器 */
  height: 50px; /* 高度为父容器高度的四分之一 */
  border-bottom: 1px solid #ccc; /* 可选：给每个区域底部添加边框，以区分它们 */
  /* 如果不想在最后一个区域显示底部边框，可以添加一个类来覆盖这个样式 */
}

.sectionMenu:last-child {
  border-bottom: none; /* 移除最后一个区域的底部边框 */
}
</style>
